<?php
include_once 'mysql.class.php';

class OrderPay {

    protected $conf;
    protected $db;

    function __construct() {
        $dbconfig = include_once __DIR__ . '/../../Apps/Common/Conf/config.php';
        $this->conf = array();
        $this->conf['hostname'] = $dbconfig['DB_HOST'];
        $this->conf['port'] = 3306;
        $this->conf['username'] = $dbconfig['DB_USER'];
        $this->conf['password'] = $dbconfig['DB_PWD'];
        $this->conf['database'] = $dbconfig['DB_NAME'];
        $this->conf['tablepre'] = 'yd_';
        $this->conf['charset'] = 'utf8';
        $this->conf['type'] = 'type';
        $this->conf['debug'] = TRUE;
        $this->conf['pconnect'] = 0;
        $this->conf['autoconnect'] = 0;

//        log_txt($this->conf, '../logs/conf-' . $out_trade_no . date('Y-m-d-H-i-s'));
        $this->db = new mysql();
        $this->db->open($this->conf);
    }

    /**
     * 完成支付订单
     */
    public function complatePay($obj) {

        $orderSN = $obj["out_trade_no"];
        $total_fee = $obj["total_fee"];
//        log_txt($obj, '../logs/complatePay-' . $orderSN);
        $data = array();
        $data["isPay"] = 1;
        $data["orderStatus"] = 0;
        $rd = array('status' => -1);
//        file_put_contents('/mnt/www/ydvd/Wxpay/logs/complatePay-' . $orderSN, print_r($obj));
        if (strlen($orderSN) == 12) {
            $orderIds = $this->db->select('orderId,orderNo,userId', 'yd_orders', 'orderSN=' . $orderSN);
            foreach ($orderIds as $v) {
                $rs = $this->db->update($data, 'yd_orders', 'orderFlag = 1 and orderStatus = -2 and orderNo = ' . $v['orderNo']);
                $this->log_orders($v['orderId'], $v['userId'], '支付成功');
                $this->logUserProfit($v['orderId']);
                $goodsList = $this->db->select('*', 'yd_order_goods', 'orderId=' . $v['orderId']);
                foreach ($goodsList as $vg) {
                    $this->decGoodsStock($vg['goodsId'], $vg['goodsNumber']);
                }
            }
        } else {
            $order = $this->db->get_one('*', 'yd_orders', 'orderNo=' . $orderSN);
            $rs = $this->db->update($data, 'yd_orders', 'orderFlag = 1 and orderStatus = -2 and orderNo = ' . $orderSN);
            $this->log_orders($order['orderId'], $order['userId'], '支付成功');
            $this->logUserProfit($order['orderId']);

            $goodsList = $this->db->select('*', 'yd_order_goods', 'orderId=' . $order['orderId']);
            foreach ($goodsList as $vg) {
                $this->decGoodsStock($vg['goodsId'], $vg['goodsNumber']);
            }
        }


        if (false !== $rs) {
            $rd['status'] = 1;
        }

        return $rd;
    }

    /**
     * 完成支付订单
     */
    public function cashDepositPay($obj) {

        $orderSN = $obj["out_trade_no"];
        $total_fee = $obj["total_fee"];
//        log_txt($obj, '../logs/cashDepositPay-' . date('Y-m-d-H-i-s'));
        Log::DEBUG("Wxpay cashDepositPay 81 line:" . json_encode($obj));
        $log = $this->db->get_one('*', 'yd_user_deposit_log', 'orderSN=' . $orderSN);
        Log::DEBUG("Wxpay cashDepositPay 83 line:" . json_encode($log));
        if ($log['type'] == 2) {
            $rs = $this->db->update(array('depositId' => $log['depositId']), 'yd_shops', 'userId=' . $log['userId']);

            $rs = $this->db->update("depositMoney = depositMoney + " . $total_fee, 'yd_shops', 'userId = ' . $log['userId']);

            $this->db->update(array('status' => 1), 'yd_user_deposit_log', 'orderSN=' . $orderSN);
            Log::DEBUG("Wxpay cashDepositPay 90 line: 保证金支付".json_encode($obj) );
            $this->MlogBalance($log['userId'], $total_fee, 1, date('Y-m-d H:i:s') . '保证金支付');
            return $rs;
        } else {
            $this->db->update("userBalance = userBalance + " . $total_fee, 'yd_users', ' userId = ' . $log['userId']);

            $this->db->update(array('status' => 1), 'yd_user_deposit_log', 'orderSN=' . $orderSN);
            Log::DEBUG("Wxpay cashDepositPay 97 line: 钱包充值".json_encode($obj) );
            $this->MlogBalance($log['userId'], $total_fee, 2, '钱包充值');
            return $rs;
        }

        return;
    }

    /**
     * 订单日志
     */
    public function log_orders($orderId, $logUserId, $logContent = '') {
        $data = array();
        $data['orderId'] = $orderId;
        $data['logUserId'] = $logUserId;
        $data['logContent'] = $logContent;
        $data['logTime'] = date('Y-m-d H:i:s');
        $rs = $this->db->insert($data, 'yd_log_orders', TRUE);

        return $rs;
    }

    /**
     * 余额日志
     */
    public function MlogBalance($userId, $price, $logType, $logContent = '') {
        $typeName = array(1 => '订单支付', 2 => '充值', 3 => '提现', 4 => '退款', 5 => '转售收益', 6 => '销售收益');
        $data = array();
        $data['userId'] = $userId;
        $data['logContent'] = $logContent;
        $data['price'] = $price;
        $data['logType'] = $logType;
        $data['typeName'] = $typeName[$logType];
        $data['logTime'] = date('Y-m-d H:i:s');
        $rs = $this->db->insert($data, 'yd_log_user_balance', TRUE);
        return $rs;
    }

    /**
     * 修改商品库存
     */
    public function decGoodsStock($goodsId, $goodsNumber) {
        $node = $this->getNodeGoodsId($goodsId);

        $this->db->update("goodsStock = goodsStock - " . $goodsNumber, 'yd_goods', ' goodsId in (' . $node . ')');
        return $rs;
    }

    public function test($value) {
        $data = array();
        $data['orderId'] = $orderId;
        $data['logUserId'] = $logUserId;
        $data['logContent'] = $logContent;
        $data['logTime'] = date('Y-m-d H:i:s');
        $rs = $this->db->insert($data, 'yd_log_orders', TRUE);
    }

    /**
     * 获取所有节点商品的ID
     * @param type $goodsId
     */
    public function getNodeGoodsId($goodsId) {
        $isSource = $this->db->get_one('*', 'yd_goods', 'goodsId=' . $goodsId);
        if ($isSource['isSource'] == 1) {
            $idArr = $this->db->select('goodsId', 'yd_goods_resale', 'sourceId=' . $goodsId);
            $node = $goodsId;
        } else {
            $sourceId = $this->db->get_one('*', 'yd_goods_resale', 'goodsId=' . $goodsId);
            $sourceId = $sourceId['sourceId'];
            $idArr = $this->db->select('goodsId', 'yd_goods_resale', 'sourceId=' . $sourceId);
            $node = $sourceId;
        }

        foreach ($idArr as $v) {
            $node .= ',' . $v['goodsId'];
        }
        $node = trim($node, ',');

        return $node;
    }

    /**
     * 记录订单利润
     * @param type $orderId
     */
    public function logUserProfit($orderId, $orderStatus = 0) {
        $goods = $this->db->get_one('*', 'yd_order_goods', 'orderId=' . $orderId);
        $percent = $this->db->get_one('fieldValue', 'yd_sys_configs', 'fieldCode="percentage"');
        $percent = 1 - $percent['fieldValue'];

        if ($goods['isSource']) {
            $goodsInfo = $this->db->get_one('*', 'yd_goods', 'goodsId=' . $goods['goodsId']);
            $data = array();
            $data['orderId'] = $orderId;
            $data['goodsId'] = $goods['goodsId'];
            $data['pgoodsId'] = 0;
            $data['shopId'] = $goods['shopId'];
            $data['orderNo'] = $goods['orderNo'];
            $data['shopPrice'] = $goods['shopPrice'];
            $data['pshopPrice'] = 0;
            $data['percent'] = 1;
            $data['profit'] = $goods['shopPrice'] * $goods['goodsNumber'];
            $data['orderStatus'] = $orderStatus;
            $data['isSource'] = $goods['isSource'];
            $data['isSelling'] = $goodsInfo['isSelling'];
            $data['isSale'] = $goodsInfo['isSale'];
            $data['isDel'] = $goodsInfo['isDel'];
            $data['goodsStatus'] = $goodsInfo['goodsStatus'];
            $data['createTime'] = date('Y-m-d H:i:s');

            $rs = $this->db->insert($data, 'yd_log_user_profit', TRUE);
        } else {
            $node = $this->db->get_one('node', 'yd_goods_resale', 'goodsId=' . $goods['goodsId']);
            $node = $node['node'];
            $goodsAll = $this->db->select('goodsId,shopPrice,shopId,isSource,isSelling,isSale,isDel,goodsStatus', 'yd_goods', 'goodsId in (' . $node . ')');
            $temp = array();
            foreach ($goodsAll as $v) {
                $temp[$v['goodsId']] = $v;
            }
            $goodsAll = $temp;
            unset($temp);

            foreach ($goodsAll as $v) {
                $data = array();
                if ($v['isSource']) {
                    $data['orderId'] = $orderId;
                    $data['goodsId'] = $v['goodsId'];
                    $data['pgoodsId'] = 0;
                    $data['shopId'] = $v['shopId'];
                    $data['orderNo'] = $goods['orderNo'];
                    $data['shopPrice'] = $v['shopPrice'];
                    $data['pshopPrice'] = 0;
                    $data['percent'] = 1;
                    $data['profit'] = $v['shopPrice'] * $goods['goodsNumber'];
                    $data['orderStatus'] = $orderStatus;
                    $data['isSource'] = $v['isSource'];
                    $data['isSelling'] = $v['isSelling'];
                    $data['isSale'] = $v['isSale'];
                    $data['isDel'] = $v['isDel'];
                    $data['goodsStatus'] = $v['goodsStatus'];
                    $data['createTime'] = date('Y-m-d H:i:s');

                    $rs = $this->db->insert($data, 'yd_log_user_profit', TRUE);
                } else {
                    $goodsResale = $this->db->get_one('*', 'yd_goods_resale', 'goodsId=' . $v['goodsId']);
                    $data['orderId'] = $orderId;
                    $data['goodsId'] = $v['goodsId'];
                    $data['pgoodsId'] = $goodsResale['parentId'];
                    $data['shopId'] = $v['shopId'];
                    $data['orderNo'] = $goods['orderNo'];
                    $data['shopPrice'] = $v['shopPrice'];
                    $data['pshopPrice'] = $goodsAll[$goodsResale['parentId']]['shopPrice'];
                    $data['percent'] = $percent;
                    $data['profit'] = (($v['shopPrice'] - $data['pshopPrice'] ) * $goods['goodsNumber']) * $percent;
                    $data['orderStatus'] = $orderStatus;
                    $data['isSource'] = $v['isSource'];
                    $data['isSelling'] = $v['isSelling'];
                    $data['isSale'] = $v['isSale'];
                    $data['isDel'] = $v['isDel'];
                    $data['goodsStatus'] = $v['goodsStatus'];
                    $data['createTime'] = date('Y-m-d H:i:s');

                    $rs = $this->db->insert($data, 'yd_log_user_profit', TRUE);
                }
            }
        }
        return;
    }

}
